<?php

class Users_Model_Index extends Light_Db_Table
{
    protected $_name = 'Users';

    protected $_rowClass = 'Users_Model_Entity_User';

    /**
     * @param string $username
     * @param string $password
     * @return boolean
     */
	public function login($username, $password)
	{
	    $select = $this->select()
	                   ->where('name = ?', $username)
	                   ->where('password = ?', $password);

	    $row = $this->fetchRow($select);

	    if ($row) {
	        $this->updateSession($row);
	        return true;
	    }

	    return false;
	}

	/**
	 * @param Light_Db_Table_Row $row
	 */
	public function updateSession(Light_Db_Table_Row $row)
	{
	    $_SESSION[LIGHT_SESSION_NAME]['identity'] = serialize($row);
	    $_SESSION[LIGHT_SESSION_NAME]['isAdmin']  = Light_Core::$db->fetchOne('SELECT admin FROM Groups WHERE id = ' . $row->groupId);
	}

	/**
	 * (non-PHPdoc)
	 * @see Light_Db_Table::validate()
	 */
    public function validate(array &$data, Light_Db_Table_Row $item = null)
    {
	    $errors = array();

	    $data = array_map('trim', $data);

	    if (isset($data['name']) && !$data['name']) {
	        $errors['name'] = 'The field is required';
	    }

	    if (isset($data['password'])) {
	        if (!$data['password']) {
	            if ($item === null) {
	                $errors['password'] = 'The field is required';
	            } else {
	                unset($data['password']);
	            }
	        } else {
	            $data['password'] = sha1($data['password']);
	        }
	    }

	    return $errors;
	}

	/**
	 * (non-PHPdoc)
	 * @see Light_Db_Table::paginate()
	 */
	public function paginate($offset, $ipp)
	{
	    $select = $this->select($this)
                	   ->setIntegrityCheck(false)
                	   ->joinInner('Groups', 'Users.groupId = Groups.id', array('name as groupName'))
                	   ->where('Groups.admin = 0')
                	   ->limit($ipp, $offset)
	                   ->order('Users.id DESC');

	    return $this->fetchAll($select);
	}

	/**
	 * (non-PHPdoc)
	 * @see Light_Db_Table::paginateCount()
	 */
	public function paginateCount()
	{
	    $select = $this->select($this)
                	   ->setIntegrityCheck(false)
                	   ->joinInner('Groups', 'Users.groupId = Groups.id', array('name as groupName'))
                	   ->where('Groups.admin = 0')
                	   ->reset('columns')
                	   ->columns('COUNT(Users.id)');

	    return $this->getAdapter()->fetchOne($select);
	}
}